<?php

include('../phpmosaic/phpmosaic.include.php');

$progressBar = null;

$x = new website();
$x->setSite($_REQUEST['site']);

class website {

	private static $isHeaderPrinted = false; 
	
	public function setSite($site) {
		
		switch ($site) {
				
			case "bilderquellen":

				$this->bilderquellen();
				break;

			case "bilderquellen_erweitern":

				$this->bilderquellenErweitern();
				break;
				
			case "clear_group":

				$this->clearGroup();
				break;
				
			case "clear_all":

				$this->clearAll();
				break;
				
			case "ueber_uns":

				$html = $this->getTemplate('templates/ueber_uns.tpl');
				$this->output($html);
				break;
				

			case "create_mosaic":

				$this->createMosaic();
				break;
				
			case "set_mosaic":
			default:

				$this->setMosaic();
				break;
		}				
	}
	

	private function clearGroup() {
		$pmip = new phpMosaicImageParser();
		$pmip->clearGroup($_REQUEST['group']);
		
		$msg = '<div id="msg_ok">Alle Bilder der Gruppe '.$_REQUEST['group'].' wurden erfolgreich gelöscht.</div>';
		return $this->bilderquellen(true, $msg);
	}
	
	private function clearAll() {
		$pmip = new phpMosaicImageParser();
		$pmip->clearAll();
		
		$msg = '<div id="msg_ok">Alle Bilderquellen wurden erfolgreich gelöscht.</div>';
		return $this->bilderquellen(true, $msg);
	}
	
	private function bilderquellen($load_config=true, $msg='') {

		$html = $this->getTemplate('templates/bilderquellen.tpl');
		global $config;
		
		if ($load_config) {
			
			$html = str_replace('-FOLDER-','',$html);			
			$html = str_replace('-GROUPS-','default',$html);			
			$html = str_replace('-INCLUDE_SUBFOLDERS-','',$html);			
			$html = str_replace('-OVERWRITE-','',$html);			
			$html = str_replace('-FORMAT_JPG-',' checked',$html);			
			$html = str_replace('-FORMAT_GIF-',' checked',$html);			
			$html = str_replace('-FORMAT_PNG-',' checked',$html);			
			$html = str_replace('-FORMAT_BMP-',' checked',$html);			
			$html = str_replace('-TN_WIDTH-',$config['thumbnail_width'],$html);			
			$html = str_replace('-TN_HEIGHT-',$config['thumbnail_height'],$html);			
			$html = str_replace('-TN_QUALITY-',$config['thumbnail_quality'],$html);			
			
			if ($config['resize_option'] == 'deform')
				$html = str_replace('-RO_DEFORM-',' checked',$html);			
			elseif ($config['resize_option'] == 'cut')
				$html = str_replace('-RO_CUT-',' checked',$html);			
			else
				$html = str_replace('-RO_IGNORE-',' checked',$html);			
			
			$html = str_replace('-RO_IGNORE-','',$html);			
			$html = str_replace('-RO_CUT-','',$html);			
			$html = str_replace('-RO_DEFORM-','',$html);			
		}
		else {
			
			$html = str_replace('-FOLDER-',$_REQUEST['folder'],$html);			
			$html = str_replace('-GROUPS-',$_REQUEST['groups'],$html);			
			$html = str_replace('-INCLUDE_SUBFOLDERS-',($_REQUEST['include_subfolders'] == '1') ? ' checked' : '',$html);			
			$html = str_replace('-OVERWRITE-',($_REQUEST['overwrite'] == '1') ? ' checked' : '',$html);			
			$html = str_replace('-FORMAT_JPG-',($_REQUEST['format_jpg'] == '1') ? ' checked' : '',$html);			
			$html = str_replace('-FORMAT_GIF-',($_REQUEST['format_gif'] == '1') ? ' checked' : '',$html);			
			$html = str_replace('-FORMAT_PNG-',($_REQUEST['format_png'] == '1') ? ' checked' : '',$html);			
			$html = str_replace('-FORMAT_BMP-',($_REQUEST['format_bmp'] == '1') ? ' checked' : '',$html);			
			$html = str_replace('-TN_WIDTH-',$_REQUEST['tn_width'],$html);			
			$html = str_replace('-TN_HEIGHT-',$_REQUEST['tn_height'],$html);			
			$html = str_replace('-TN_QUALITY-',$_REQUEST['tn_quality'],$html);			
			
			if ($_REQUEST['resize_option'] == 'deform')
				$html = str_replace('-RO_DEFORM-',' checked',$html);			
			elseif ($_REQUEST['resize_option'] == 'cut')
				$html = str_replace('-RO_CUT-',' checked',$html);			
			else
				$html = str_replace('-RO_IGNORE-',' checked',$html);			
			
			$html = str_replace('-RO_IGNORE-','',$html);			
			$html = str_replace('-RO_CUT-','',$html);			
			$html = str_replace('-RO_DEFORM-','',$html);			
		}
		
		// Gruppen herausfinden und ausgeben
		
		$groupsHtml = "Keine Bilder vorhanden!";
		
		$pmip = new phpMosaicImageParser();
		$groupsArr = $pmip->getGroupsArray();
		
		if (count($groupsArr) > 0) {
			$groupsHtml = '<ul>';
			foreach ($groupsArr as $key => $group) {
				$groupsHtml .= '<li>' . $group['name'] . ' (' . $group['counter'] . ') - ' . '<a href="index.php?site=clear_group&group=' . urlencode($group['name']) . '">Löschen</a></li>';
			}
			$groupsHtml .= '</ul>';
		}
		
		// Gruppen ausgeben
		$html = str_replace('-GROUPS_LIST-',$groupsHtml,$html);
		
		// Ausgabe
		$html = str_replace('-MSG-',$msg,$html);			
		$this->output($html);
	}
	
	
	private function bilderquellenErweitern() {
		
		$overwriteExistingImages = (intval($_REQUEST['overwrite']) > 0) ? true : false;
		$includeSubfolders = (intval($_REQUEST['include_subfolders']) > 0) ? true : false;
		$img_ext_array = array();
		$msg = '';
		
		if (intval($_REQUEST['format_jpg']) > 0) {
			
			$img_ext_array[] = "jpg";
			$img_ext_array[] = "jpeg";
		}

		if (intval($_REQUEST['format_png']) > 0)
			$img_ext_array[] = "png";
			
		if (intval($_REQUEST['format_bmp']) > 0)
			$img_ext_array[] = "bmp";
		
		if (intval($_REQUEST['format_gif']) > 0)
			$img_ext_array[] = "gif";
		
		if (count($img_ext_array) > 0) {
			
			$this->outputHeader();
				
			global $progressBar;
			$progressBar = self::getNewProgressBar(100,'Bilder werden indiziert ...'); 

			$pmip = new phpMosaicImageParser();
			$pmip->showErrorMessages(false);
			$pmip->setTimeLimit(0);
			$pmip->setThumbnailSize(intval($_REQUEST['tn_width']), intval($_REQUEST['tn_height']));
			$pmip->setThumbnailQuality(intval($_REQUEST['tn_quality']));
			$pmip->includeSubfolders($includeSubfolders);
			$pmip->overwriteExistingImages($overwriteExistingImages);
			$pmip->setImageExtensions($img_ext_array);
			$pmip->registerProgressCallback("updateParserProgressBar");
			$error = $pmip->parseImageFolder($_REQUEST['folder'], $_REQUEST['groups']);
			
			if ($error > 0) {
				
				$msg = '<div id="msg_error">Der angegebene Foto Ordner existiert nicht</div>';
			}
			else {
				
				$msg = '<div id="msg_ok">Es wurden '.$pmip->getParsedImages().' Fotos erfolgreich initialisiert</div>';
			}
			
		}
		else {

			$msg = '<div id="msg_error">Bitte wählen Sie mindestens ein Format aus.</div>';
		}
			
		$this->bilderquellen(false, $msg);
	}
	
	
	private function setMosaic($load_config=true, $msg='') {
		
		$html = $this->getTemplate('templates/mosaic.tpl');
		$pmic = new phpMosaicImageCreator();
		$groups_array = $pmic->getGroupsArray();
		$groups = "keine Gruppen vorhanden";
		
		if (count($groups_array) > 0) {
			
			$groups = "";
			foreach($groups_array as $key => $value) {
				
				$groups .= '<tr><td><input type="checkbox" value="1" name="'.$value['name'].'"';  
				$groups .= (intval($_REQUEST[$value['name']]) == '1') ? ' checked>' : '>';
				$groups .= '</td><td>'.$value['name'].'</td></tr>';
			}
		}
		
		if ($load_config) {
			
			$html = str_replace('-QUALITY-',75,$html);			
			$html = str_replace('-RANGE-','0',$html);			
			$html = str_replace('-DISTANCE-','10',$html);			
		}
		else {
			
			$html = str_replace('-QUALITY-',$_REQUEST['quality'],$html);			
			$html = str_replace('-RANGE-',$_REQUEST['range'],$html);			
			$html = str_replace('-DISTANCE-',$_REQUEST['distance'],$html);			
		}
		
		$sizes = $pmic->getThumbnailSizesArray();

		if (count($sizes) > 0) {
			
			foreach ($sizes as $size) {
				
				$sel = $size['width'] . "x" . $size['height'];
				
				if ($sel == $_REQUEST['tn_format'])
					$tn_options .= '<option selected value="'.$sel.'">'.$sel.'</option>';
				else
					$tn_options .= '<option value="'.$sel.'">'.$sel.'</option>';
			}
		}
		
		$html = str_replace('-GROUPS-',$groups,$html);			
		$html = str_replace('-TN_OPTIONS-',$tn_options,$html);	
		$html = str_replace('-MSG-',$msg,$html);	
		$this->output($html);
	}
	
	
	
	private function createMosaic() {
		
		if ($_FILES['datei']['size'] > 0) {

			if (in_array($this->_getFileExtention($_FILES['datei']['name']), array('gif','jpg','jpeg','bmp','png','tif'))) {

				$timestamp = time();
				$src = "tmp/src_" . $timestamp . "." . $this->_getFileExtention($_FILES['datei']['name']); 
				$target = "tmp/mosaic_" . $timestamp . ".jpg";
				copy($_FILES['datei']['tmp_name'],$src);
				$dim = split("x",$_REQUEST['tn_format']);
				
				$this->outputHeader();
				
				global $progressBar;
				$progressBar = self::getNewProgressBar(100,'Mosaik wird erstellt ...'); 
				
				$pmic = new phpMosaicImageCreator();
				$groups_array = $pmic->getGroupsArray();
				$groups = array();
				
				if (count($groups_array) > 0) {
					
					foreach($groups_array as $key => $value) {
						
						if (intval($_REQUEST[$value['name']]) != '1') 
							$groups[] = $value['name'];
					}
				}
				

				$pmic->showErrorMessages(false);
				$pmic->setTimeLimit(0);
				$pmic->setSourceImageFile($src);
				$pmic->setThumbnailSize($dim[0], $dim[1]);
				$pmic->setQuality(intval($_REQUEST['quality']));
				$pmic->setRange(intval($_REQUEST['range']));
				$pmic->setDistance(intval($_REQUEST['distance']));
				$pmic->setGroupsFilter($groups);
				$pmic->disableOptimiser();
				$pmic->registerProgressCallback("updateCreateProgressBar");
				$error = $pmic->createMosaicImage($target);

				if ($error > 0) {
					
					$this->setMosaic(false, '<div id="msg_error">Nicht genug Thumbnails</div>');			
				}
				else {
					
					$html = $this->getTemplate('templates/mosaic_created.tpl');
					unlink($src);
					$html = str_replace("-TIMESTAMP-",$timestamp,$html);
					
					$this->outputHtml($html);
					$this->outputFooter();
				}
			}
			else {
				
				$this->setMosaic(false, '<div id="msg_error">ungültiges Dateiformat</div>');			
			}
		}
		else {
			
			$this->setMosaic(false, '<div id="msg_error">Keine Datei ausgewählt</div>');			
		}
	}
	
	
	private function _getFileExtention($string) {
		
		$ext = strrchr($string,".");
		$ext = str_replace(".","",$ext);
		return strtolower($ext);
	}
	
	
	private function output($html) {
		$this->outputHeader();
		$this->outputHtml($html);
		$this->outputFooter();		
	}
	
	private function outputHeader() {
		if (!self::$isHeaderPrinted) {
			echo $this->getTemplate('templates/header.tpl');
			self::$isHeaderPrinted = true;
		}
	}
	
	private function outputHtml($html) {
		echo $html;
	}
	
	private function outputFooter() {
		echo $this->getTemplate('templates/footer.tpl');
	}
	
	
	private function getTemplate($datei) {

		$text_array = file($datei);
		return implode($text_array,"");
	}
	
	###############################################################################
	
	public static function getNewProgressBar($elements=100, $firstText="Loading") {
		
		require_once(dirname(__FILE__) . '/lib/ProgressBar.class.php');
		
		$progressBar = new ProgressBar();
		$progressBar->setMessage($firstText);
		$progressBar->setAutohide(true);
		$progressBar->setSleepOnFinish(1);
		
		$progressBar->initialize($elements);
		
		return $progressBar;
	}
	
}

function updateCreateProgressBar($var) {
	global $progressBar;
	
	if (is_object($progressBar)) {
		$progressBar->increase();
		$progressBar->setMessage('Mosaik zu ' . $var . '% fertig!');
		$progressBar->setForegroundColor('#3F41FF');
	}
}

function updateParserProgressBar($var) {
	global $progressBar;
	
	if (is_object($progressBar)) {
		$progressBar->increase();
		$progressBar->setMessage('Die Bilder wurden zu ' . $var . '% indiziert!');
		$progressBar->setForegroundColor('#3F41FF');
	}
}




?>